package com.mvvmhabit.org.binding.viewadapter.image

import android.text.TextUtils
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.mvvmhabit.org.R

/**
 * @Date: 2020/10/30 15:55
 * @Author:小妖
 * @Description: ImageView
 * url: 图片地址
 * placeholderRes： 本地资源
 */

@BindingAdapter(value = ["url", "placeholderRes", "isStaggerItem"], requireAll = false)
fun setImageUri(view: ImageView, url: String, placeholderRes: Int, isStaggerItem: Boolean) {
    if (!TextUtils.isEmpty(url)) {
        //屏幕的宽度(px值）
        //屏幕的宽度(px值）
        if (isStaggerItem) {
            val screenWidth: Int = view.context.resources.displayMetrics.widthPixels
            //Item的宽度，或图片的宽度
            //Item的宽度，或图片的宽度
            val width = screenWidth / 2
            Glide.with(view.context)
                .load(url)
                .apply(
                    RequestOptions().placeholder(placeholderRes).override(width).error(
                        ContextCompat.getDrawable(
                            view.context,
                            R.mipmap.ic_launcher
                        )
                    )
                )
                .into(view)
        } else {
            Glide.with(view.context)
                .load(url)
                .apply(
                    RequestOptions().placeholder(placeholderRes).error(
                        ContextCompat.getDrawable(
                            view.context,
                            R.mipmap.ic_launcher
                        )
                    )
                )
                .into(view)
        }
    }
}

@BindingAdapter(value = ["url", "placeholderRes"], requireAll = false)
fun setImageUri(view: AppCompatImageView, url: String, placeholderRes: Int) {
    if (!TextUtils.isEmpty(url)) {
        Glide.with(view.context)
            .load(url)
            .apply(
                RequestOptions().placeholder(placeholderRes).error(
                    ContextCompat.getDrawable(
                        view.context,
                        R.mipmap.ic_launcher
                    )
                )
            )
            .into(view)
    }
}

